package cn.flying.base.web.auth.handler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.web.auth.configuration.LoginUser;
import cn.flying.base.web.auth.domain.SysLoginLog;
import cn.flying.base.web.auth.exception.CaptchaException;
import cn.flying.base.web.auth.service.SysUserService;

/**
 * @description: 登录认证失败处理类
 * @author: lvyong
 * @date: 2023年05月25日 12:54
 * @version: 1.0
 */
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysUserService sysUserService;

    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.error("登录失败！", exception);
        Rt rt;
        //判断异常类型
        if (exception instanceof AccountExpiredException) {
            rt = Rt.error(RtCodeEnum.R10011);
        } else if (exception instanceof BadCredentialsException) {
            rt = Rt.error(RtCodeEnum.R10003);
        } else if (exception instanceof CredentialsExpiredException) {
            rt = Rt.error(RtCodeEnum.R10010);
        } else if (exception instanceof DisabledException) {
            rt = Rt.error(RtCodeEnum.R10012);
        } else if (exception instanceof LockedException) {
            rt = Rt.error(RtCodeEnum.R10002);
        } else if (exception instanceof InternalAuthenticationServiceException) {
            rt = Rt.error(RtCodeEnum.R10001);
        } else if (exception instanceof CaptchaException) {
            rt = Rt.error(RtCodeEnum.R10004);
        } else {
            rt = Rt.error(RtCodeEnum.R10013);
        }

        try {
            LoginUser loginUser = sysUserService.findUserByUsername(request.getParameter("username"));
            if (Objects.nonNull(loginUser)) {
                //保存登录日志
                SysLoginLog loginLog = new SysLoginLog();
                loginLog.setUserId(loginUser.getUserId());
                loginLog.setUserName(loginUser.getUsername());
                loginLog.setName(loginUser.getName());
                //I 登入成功 O 登出成功  F 登入失败  T 会话失效
                loginLog.setHappenType("F");
                loginLog.setHappenTime(new Date());
                loginLog.setHappenIp(Ft.Network.getIpAddress(request));
                loginLog.setRemark("用户登录失败，" + rt.getMsg());
                loginLog.setTenantId(loginUser.getTenantId());
                loginLog.setCreatedBy(loginUser.getUsername());
                loginLog.setCreatedTime(new Date());
                loginLog.setUpdatedBy(loginUser.getUsername());
                loginLog.setUpdatedTime(new Date());
                loginLog.setRevision(0L);
                sysUserService.insertLoginLog(loginLog);
            }
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //登录成功返回用户信息
        out.write(JSON.toJSONString(rt));
        out.flush();
        out.close();
    }
}
